package com.lulin.mall.ware.service.impl;

import com.lulin.common.constant.WareConstant;
import com.lulin.mall.ware.entity.PurchaseDetailEntity;
import com.lulin.mall.ware.service.PurchaseDetailService;
import com.lulin.mall.ware.service.WareSkuService;
import com.lulin.mall.ware.vo.MergeVO;
import com.lulin.mall.ware.vo.PurchaseDoneVO;
import com.lulin.mall.ware.vo.PurchaseItemDoneVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lulin.common.utils.PageUtils;
import com.lulin.common.utils.Query;

import com.lulin.mall.ware.dao.PurchaseDao;
import com.lulin.mall.ware.entity.PurchaseEntity;
import com.lulin.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService detailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询采购单的状态为：新增 或者 已经分配的采购单信息
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        //添加查询的条件(新增 和 已经分配的)
        wrapper.eq("status", 0).or().eq("status", 1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 将采购需求合并
     * 有2种情况：
     * 1、采购人员进行手动合并，传来采购单的id；
     * 2、进行自动创建；
     *
     * @param mergeVO
     * @return
     */
    @Transactional
    @Override
    public Integer merge(MergeVO mergeVO) {
        Long purchaseId = mergeVO.getPurchaseId();
        if (purchaseId == null) {
            //新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            //新建状态
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //判断采购单的状态，如果是已领取或者已完成，就不能合点了。只能是新建或者已分配才能合单
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        //大于 2:已领取
        if (purchaseEntity.getStatus() > WareConstant.PurchaseStatusEnum.RECEIVE.getCode()) {
            //该采购单。不能合单
            return -1;
        }

        //整合采购需求单
        List<Long> items = mergeVO.getItems();
        final long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> list = items.stream().map(i -> {
            //封装需求单
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            // 更新每一条 需求单的 采购单编号
            detailEntity.setId(i);
            detailEntity.setPurchaseId(finalPurchaseId);
            //已分配
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode());

            return detailEntity;
        }).filter(id -> {
            //通过id，找到数据
            PurchaseDetailEntity item = detailService.getById(id);
            //对状态进行过滤
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()
                    || item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode()) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());

        if (list != null && list.size() > 0) {
            //批量更新
            detailService.updateBatchById(list);
        }

        // 更新对应的采购单的更新时间
        PurchaseEntity entity = new PurchaseEntity();
        entity.setId(purchaseId);
        entity.setUpdateTime(new Date());
        this.updateById(entity);

        return 1;
    }

    /**
     * 领取采购单
     * 1、领取采购单的状态只能是（新增或者已经分配的采购单），其他不能领取
     * 2、更新采购单的状态，已领取；
     * 3、更新采购项的状态为：正常采购；
     *
     * @param ids
     */

    @Override
    public void received(List<Long> ids) {
        //1、领取采购单的状态只能是（新增或者已经分配的采购单），其他不能领取
        List<PurchaseEntity> list = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(item -> {
            //状态为：新建  或者 已分配
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGED.getCode()) {
                return true;
            }
            return false;
            //设置采购单的一些信息
        }).map(item -> {
            // 设置更新时间
            item.setUpdateTime(new Date());
            //设置更新采购单的状态为——已领取
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return item;
        }).collect(Collectors.toList());

        //2、更新采购单的状态，已领取；
        this.updateBatchById(list);

        //3、更新采购项的状态为：正常采购；
        for (Long id : ids) {
            //根据采购单id，找到对应的采购项对象
            List<PurchaseDetailEntity> detailEntities = detailService.listDetailByPurchaseId(id);
            //封装采购项信息
            List<PurchaseDetailEntity> collect = detailEntities.stream().map(item -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(item.getId());
                //状态：正在采购
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return entity;
            }).collect(Collectors.toList());
            //更新采购项
            detailService.updateBatchById(collect);
        }
    }

    /**
     * 完成采购操作
     *
     * @param vo
     */
    @Transactional
    @Override
    public void done(PurchaseDoneVO vo) {
        //获取采购单id编号
        Long id = vo.getId();

        //2、改变采购项状态
        //注意：不能直接更新采购单状态为“已完成”，因为是根据采购需求来决定的，要看采购项的状态是否全部完成
        Boolean flag = true;//记录采购的状态，默认为完成
        //获取所有的采购项
        List<PurchaseItemDoneVO> items = vo.getItems();
        List<PurchaseDetailEntity> list = new ArrayList<>();
        for (PurchaseItemDoneVO item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                //该采购项，采购出现了问题
                flag = false;
                detailEntity.setStatus(item.getStatus());
            } else {
                //已完成
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3、采购项采购成功的，要进行入库操作——wms_ware_sku
                //根据采购项id，查询出对应的采购项信息
                PurchaseDetailEntity detailEntity1 = detailService.getById(item.getItemId());
                //入库操作（商品id，仓库id，商品数量）
                wareSkuService.addStock(detailEntity1.getSkuId(),detailEntity1.getWareId(),detailEntity1.getSkuNum());
            }
            //菜单项的id
            detailEntity.setId(item.getItemId());
            //更新采购项的状态——一条一条更新，有更多条时，效率太低了
            // detailService.updateById(detailEntity);
            list.add(detailEntity);
        }
        //批量更新采购项
        detailService.updateBatchById(list);

        //1、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        // true：已完成   false:有异常
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode()
                : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        //更新采购单的信息
        this.updateById(purchaseEntity);
    }

}
